package com.charm.frameworkarou.animation

import android.graphics.Camera
import android.view.ContextThemeWrapper
import android.view.animation.Animation
import android.view.animation.Transformation

/**
 * Created by tools on 2018/1/26.
 */
class Rotate3dAnimation(context: ContextThemeWrapper, fromDegrees: Float, toDegrees: Float,
                        centerX: Float, centerY: Float, depthZ: Float, reverse: Boolean) : Animation() {
    /**
     * 开始角度
     */
    private var mFromDegrees: Float = fromDegrees
    /**
     * 结束角度
     */
    private var mToDegrees: Float = toDegrees
    /**
     * 中心点
     */
    private var mCenterX: Float = centerX
    private var mCenterY: Float = centerY
    /**
     * 深度
     */
    private var mDepthZ: Float = depthZ
    /**
     * 是否需要扭曲
     */
    private var mReverse: Boolean = reverse
    /**
     * 摄像头
     */
    private var mCamera: Camera? = null
    /**
     * 上下文
     */
    internal var context: ContextThemeWrapper = context
    /**
     * 屏幕密度（默认值为1）
     */
    internal var scale = 1f

    override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) {
        super.initialize(width, height, parentWidth, parentHeight)
        mCamera = Camera()
    }

    /**
     * 生成Transformation
     *
     * @param interpolatedTime
     * @param t
     */
    override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
        val fromDegrees = mFromDegrees
        // 生成中间角度
        val degrees = fromDegrees + (mToDegrees - fromDegrees) * interpolatedTime


        val centerX = mCenterX
        val centerY = mCenterY
        val camera = mCamera

        val matrix = t.matrix

        camera!!.save()
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime)
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime))
        }
        camera.rotateY(degrees)
        // 取得变换后的矩阵
        camera.getMatrix(matrix)
        camera.restore()
        val mValues = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)
        //获取数值
        matrix.getValues(mValues)
        //数值修正
        mValues[6] = mValues[6] / scale
        //重新赋值
        matrix.setValues(mValues)

        matrix.preTranslate(-centerX, -centerY)
        matrix.postTranslate(centerX, centerY)
    }
}